/*
Copyright (C) 2022-2024 Inspur Corp. All Rights Reserved.

SPDX-License-Identifier: Apache-2.0
*/
package utils

import (
	"git.cloud.inspur.com/ichain/ichain-protos-go/common"
	"git.cloud.inspur.com/ichain/ichain-protos-go/inode"
	"github.com/golang/protobuf/proto"
	"github.com/pkg/errors"
)

func GetPayload(e *common.Envelope) (*common.Payload, error) {
	payload := &common.Payload{}
	err := proto.Unmarshal(e.Payload, payload)
	return payload, errors.Wrap(err, "error unmarshaling Payload")
}

func UnmarshalChainHeader(bytes []byte) (*common.ChainHeader, error) {
	chdr := &common.ChainHeader{}
	err := proto.Unmarshal(bytes, chdr)
	return chdr, errors.Wrap(err, "error unmarshaling ChainHeader")
}

func UnmarshalSignatureHeader(bytes []byte) (*common.SignatureHeader, error) {
	sh := &common.SignatureHeader{}
	if err := proto.Unmarshal(bytes, sh); err != nil {
		return nil, errors.Wrap(err, "error unmarshaling SignatureHeader")
	}
	return sh, nil
}

func UnmarshalTransaction(txBytes []byte) (*inode.Transaction, error) {
	tx := &inode.Transaction{}
	err := proto.Unmarshal(txBytes, tx)
	return tx, errors.Wrap(err, "error unmarshaling Transaction")

}

func UnmarshalContractActionPayload(capBytes []byte) (*inode.ContractActionPayload, error) {
	cap := &inode.ContractActionPayload{}
	err := proto.Unmarshal(capBytes, cap)
	return cap, errors.Wrap(err, "error unmarshaling ContractActionPayload")
}

func UnmarshalContractProposalPayload(bytes []byte) (*inode.ContractProposalPayload, error) {
	cpp := &inode.ContractProposalPayload{}
	err := proto.Unmarshal(bytes, cpp)
	return cpp, errors.Wrap(err, "error unmarshaling ContractProposalPayload")
}

func UnmarshalContractInvocationSpec(input []byte) (*inode.ContractInvocationSpec, error) {
	cis := &inode.ContractInvocationSpec{}
	err := proto.Unmarshal(input, cis)
	return cis, errors.Wrap(err, "error unmarshaling ContractInvocationSpec")
}
